package controller

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/topaz-h/gin-web/params"
	"github.com/topaz-h/gin-web/tools"
)

// IndexController 结构体
type IndexController struct {
}

// Router 路由
func (i *IndexController) Router(engine *gin.Engine) {
	// 首页
	engine.Handle("GET", "/", i.home)
	engine.POST("/upload_file", tools.UploadFile())
	// token
	engine.POST("/create_token", tools.AuthHandler(), i.homeHandler)
	engine.POST("/vertify", tools.JWTAuthMiddleware(), i.homeHandler)
	// validator
	engine.POST("/signup", i.validator)
}

// home MVC中的C 解析"/"
func (i *IndexController) home(c *gin.Context) {
	time.Sleep(5 * time.Second)
	c.JSON(http.StatusOK, map[string]interface{}{
		"message": "延迟 5 s hello world!",
	})
}

func (i *IndexController) homeHandler(c *gin.Context) {
	username := c.MustGet("username").(string)
	c.JSON(http.StatusOK, gin.H{
		"code": 2000,
		"msg":  "success",
		"data": gin.H{"username": username},
	})
}

func (i *IndexController) validator(c *gin.Context) {
	var u params.SignUpParam
	if err := c.ShouldBind(&u); err != nil {
		tools.TranslateErrors(c, err)
		return
	}
	// 保存入库等操作...
	tools.Success(c, u)
}
